﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Lib.CommonForm;

namespace AUI
{
    public partial class frmUsersList : FormBase
    {
        DataTable _dt = null;
        public DataRow dr { get; set; }
        public frmUsersList()
        {
            InitializeComponent();
        }
  
        public void Show_Form()
        {
            //Dành cho admin
            this._isSelect = true;
            this._keyWord = "";
            this._branchId = FormGlobals.BranchID;
            btnSelect.Visible = _isSelect;
            cboBranch.ComboBox.SelectedValue = _branchId;
            this.Show();
        }

        public void Show_Form(string formText, bool isSelect, int branchID, string keyWord)
        {
            if (formText != "")
            {
                this.Text = formText;
                this.TabText = formText;
            }
            this._isSelect = isSelect;
            this._keyWord = keyWord;
            this._branchId = branchID;
            btnSelect.Visible = _isSelect;
            if (isSelect)
            {
                txtKeyword.Text = keyWord;
                cboBranch.Enabled = false;
                cboBranch.ComboBox.SelectedValue = _branchId;
            }
            this.Show();
        }
        protected override void Init_Control()
        {
            _listRole = tbl_RoleRight_Controller.Instance().GetInfo("NguoiDung");

            FormGlobals.dgv_SelectionMode_FullRowSelect(dgvList);

            FormGlobals.dgv_AutoSizeColumnsMode_BeginLoad(dgvList);

            dgvList.BorderStyle = BorderStyle.FixedSingle;

            TextBoxFind tbf = new TextBoxFind(txtKeyword, "");
            FormGlobals.dgv_AddColumn_TextBox(dgvList, "UserName", "Tên đăng nhập", "", 1, true, true);
            FormGlobals.dgv_AddColumn_TextBox(dgvList, "EmployeeCode", "Mã nhân viên", "", 1, true, true);
            FormGlobals.dgv_AddColumn_TextBox(dgvList, "EmployeeName", "Họ và tên", "", 1, true, true);
            FormGlobals.dgv_AddColumn_TextBox(dgvList, "Address", "Địa chỉ", "", 1, true, true);
            FormGlobals.dgv_AddColumn_TextBox(dgvList, "Email", "Email", "", 1, true, true);
            FormGlobals.dgv_AddColumn_TextBox(dgvList, "Phone", "Điện thoại", "", 1, true, true);
            FormGlobals.dgv_AddColumn_TextBox(dgvList, "Mobile", "Di động", "", 1, true, true);
            FormGlobals.dgv_AddColumn_TextBox(dgvList, "Position", "Chức vụ", "", 1, true, true);
            FormGlobals.dgv_AddColumn_TextBox(dgvList, "BranchName", "Đơn vị", "", 1, true, true);
            FormGlobals.dgv_AddColumn_TextBox(dgvList, "DepartmentName", "Bộ phận", "", 1, true, true);
            FormGlobals.dgv_AddColumn_TextBox(dgvList, "UserId", "", "", 1, false, false);
            FormGlobals.dgv_AddColumn_TextBox(dgvList, "EmployeeId", "", "", 1, false, false);

            FormGlobals.dgv_ColumnsSortMode(dgvList, DataGridViewColumnSortMode.Programmatic);

            LoadComboBox.BranchID_Filter(cboBranch);

            LoadComboBox.DepartmentID_Filter(cboDepartment, Globals.ToInt32(cboBranch.ComboBox.SelectedValue));

            ShowLoadData();
            
        }

        private void ShowLoadData()
        {
            _IsLoading = true;
            _keyWord = Globals.GetKeyWord(txtKeyword.Text);
            _branchId = Globals.ToInt32(cboBranch.ComboBox.SelectedValue);
            _departmentId = Globals.ToInt32(cboDepartment.ComboBox.SelectedValue);

            //Splash.Show(LoadData, "");
            FormGlobals.App_ProgressShow(new MethodInvoker(LoadData));
            dgvList.DataSource = _dt;
            PageIndex(lblPageIndex, lblTotalRows);
            Control_EnableByRole(this, dgvList.RowCount);
            _IsLoading = false;
        }

        private void LoadData()
        {
            _dt = tbl_Users_Controller.Instance().GetList(out _itemCount, _orderBy, _orderDirection, _currentPage, _pageSize, _keyWord, _branchId, _departmentId);
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {

            if (dgvList.SelectedRows.Count > 0)
            {
                if (new frmUserInfo().Show_Form(dr) == DialogResult.OK)
                {
                    ShowLoadData();

                    //Re selection on datagridview
                    FormGlobals.dgv_ReSelection(dgvList, "Username", _userName);
                }
            }
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            if (new frmUserInfo().Show_Form(null) == DialogResult.OK)
            {
                _currentPage = 0;
                ShowLoadData();
            }
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            if (dgvList.SelectedRows.Count > 0)
            {
                if (_userName.ToLower().Equals(FormGlobals.strUserName.ToLower()))
                    FormGlobals.Message_Warning("Bạn đang đăng nhập bằng tên đăng nhập này nên không xóa được.");
                else
                {
                    if (FormGlobals.Message_Confirm(UIMessage.QUESTION_DELETE))
                    {
                        if (tbl_Users_Controller.Instance().Delete(_userName))
                        {
                            FormGlobals.Message_InTaskbar(UIMessage.DETETE_COMPLETE);
                            ShowLoadData();
                        }
                        else
                            FormGlobals.Message_Error(new Exception( UIMessage.DETETE_ERROR));
                    }
                }
            }
        }

        private void dgvList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
                if (_isSelect)
                    btnSelect.PerformClick();
                else
                    if (btnEdit.Enabled)
                        btnEdit.PerformClick();
        }


        private void btnFirst_Click(object sender, EventArgs e)
        {
            if (_currentPage > 0)
            {
                _currentPage = 0;
                ShowLoadData();
            }
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (_totalPage > 0 && _currentPage < _totalPage - 1)
            {
                _currentPage++;
                ShowLoadData();
            }
        }

        private void btnPrevious_Click(object sender, EventArgs e)
        {
            if (_currentPage > 0)
            {
                _currentPage--;
                ShowLoadData();
            }
        }

        private void btnLast_Click(object sender, EventArgs e)
        {
            if (_totalPage > 0 && _currentPage < _totalPage - 1)
            {
                _currentPage = _totalPage - 1;
                ShowLoadData();
            }
        }

        void ReLoad()
        {
            if (!_IsLoading)
            {
                _currentPage = 0;
                ShowLoadData();
            }
        }

        private void btnSearh_Click(object sender, EventArgs e)
        {
            ReLoad();
        }


        private void cboBranch_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!_IsLoading)
            {
                LoadComboBox.DepartmentID_Filter(cboDepartment, Globals.ToInt32(cboBranch.ComboBox.SelectedValue));
                ReLoad();
            }
        }

        private void cboDepartment_SelectedIndexChanged(object sender, EventArgs e)
        {
            ReLoad();
        }

        private void btnPutout_Click(object sender, EventArgs e)
        {
            //if (dgvList.SelectedRows.Count > 0)
            //{
            //    userName = dgvList.SelectedRows[0].Cells["Username"].Value.ToString();
            //    UserClient wcfUser = UIService.User();
            //    if (wcfUser.User_PutOut(userName))
            //    {
            //        Program.Message_InTaskbar(UIMessage.PUT_COMPLETE);
            //    }
            //    else
            //    {
            //        Program.Message_Stop(this, "User này có đang sử dụng đâu mà đẩy.");
            //    }
            //    wcfUser.Close();
            //}
        }

        private void frmUserList_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyData)
            {
                case Keys.Down:
                    if (dgvList.Rows.Count > 0)
                    {
                        dgvList.Focus();
                    }
                    break;
                case Keys.Insert:
                case Keys.Control | Keys.Enter:
                    btnSelect.PerformClick();
                    break;
            }
        }

        private void mnuLock_Click(object sender, EventArgs e)
        {
            //if (dgvList.SelectedRows.Count > 0)
            //{
            //    userName = dgvList.SelectedRows[0].Cells["Username"].Value.ToString();
            //    if (Convert.ToBoolean(dgvList.SelectedRows[0].Cells["IsAnonymous"].Value))
            //    {
            //        //FormGlobals.MsgBox("Đã khóa rồi mà.");
            //        return;
            //    }
            //    if (!userName.ToLower().Equals(Program.strUserName.ToLower()))
            //    {
            //        if (Program.Message_Question("Bạn có chắc chắn khóa người dùng này?") == DialogResult.Yes)
            //        {
            //            UserClient wcfUser = UIService.User();
            //            if (wcfUser.User_IsAnonymous(userName, true))
            //            {
            //                Program.Message_InTaskbar(UIMessage.LOCK_COMPLETE);
            //                ShowLoadData();
            //            }
            //            else
            //            {
            //                Program.Message_Stop(this, "Có lỗi không khóa được.");
            //            }
            //            wcfUser.Close();
            //        }
            //    }
            //    else
            //        Program.Message_Stop(this, "Không thể khóa.");
            //}

        }

        private void mnuOpenLock_Click(object sender, EventArgs e)
        {
            //if (dgvList.SelectedRows.Count > 0)
            //{
            //    userName = dgvList.SelectedRows[0].Cells["Username"].Value.ToString();
            //    if (!Convert.ToBoolean(dgvList.SelectedRows[0].Cells["IsAnonymous"].Value))
            //    {
            //        //FormGlobals.MsgBox("Đã mở khóa rồi mà.");
            //        return;
            //    }
            //    if (!userName.ToLower().Equals(Program.strUserName.ToLower()))
            //    {
            //        if (Program.Message_Question("Bạn có chắc chắn mở khóa cho người dùng này?") == DialogResult.Yes)
            //        {
            //            UserClient wcfUser = UIService.User();
            //            if (wcfUser.User_IsAnonymous(userName, false))
            //            {
            //                Program.Message_InTaskbar(UIMessage.UNLOCK_COMPLETE);
            //                ShowLoadData();
            //            }
            //            else
            //            {
            //                Program.Message_Stop(this, "Có lỗi không khóa được.");
            //            }
            //            wcfUser.Close();
            //        }
            //    }
            //}
        }


        private void dgvList_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            //if (dgvList.DataSource == null) return;
            //if (e.ColumnIndex == dgvList.Columns["IsAnonymous"].Index)
            //{
            //    if (Convert.ToBoolean(e.Value))
            //        e.Value = "Đã khóa";
            //    else
            //        e.Value = "";
            //}
        }

        private void txtKeyword_KeyDown(object sender, KeyEventArgs e)
        {

        }

        private void dgvList_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            dgv_ColumnHeaderMouseClick(sender, e, delegate { ShowLoadData(); });
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            ReLoad();
        }

        private void btnExcel_Click(object sender, EventArgs e)
        {
            if (!FormGlobals.Message_Confirm("Bạn có chắc chắn " + btnExcel.Text + "?")) return;
            try
            {
                int out1 = 0;
                DataTable dtExcel = tbl_Users_Controller.Instance().GetList(out out1, _orderBy, _orderDirection, 0, _itemCount, _keyWord, 0, 0);
                ReadExcelFile.MSExcelExport(FormGlobals.dgv_GetColumnHeaderText(dgvList, dtExcel), this.Text);
            }
            catch (Exception ex)
            {
                FormGlobals.Message_Warning(ex.Message);
                return;
            }
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {

            if (dgvList.SelectedRows.Count > 0)
            {
                _dlgResult = DialogResult.OK;
                this.Close();
            }

        }

        private void dgvList_SelectionChanged(object sender, EventArgs e)
        {
            if (!_IsLoading)
            {
                if (dgvList.SelectedRows.Count > 0)
                {
                    dr = FormGlobals.dgv_GetDataRow(dgvList);
                    _userName = dr["UserName"].ToString();
                }
            }
        }



        //private void mnuPutOut_Click(object sender, EventArgs e)
        //{
        //    if (dgvList.SelectedRows.Count > 0)
        //    {
        //        string userName = dgvList.SelectedRows[0].Cells["Username"].Value.ToString();
        //        if (userName.ToLower().Equals(Program.strUserName.ToLower()))
        //            FormGlobals.MsgBox(UIMessage.NODATA);
        //        else
        //        {
        //            UserClient wcfUser = UIService.User();
        //            if (wcfUser.User_PutOut(userName))
        //            {
        //                Program.taskbarNotifier.Show(Program.ProjectTitle, "Đã đẩy thành công", Program.TimeUp, Program.TimeShow, Program.TimeDown);
        //            }
        //            else
        //            {
        //                FormGlobals.MsgBox("User này có đang sử dụng đâu mà đẩy.");
        //            }
        //        }
        //    }
        //}

    }
}
